package com.youlai.boot.system.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.common.util.ExcelUtils;
import com.youlai.boot.system.model.entity.TomYzTable;
import com.youlai.boot.system.service.TomTableService;
import com.youlai.boot.system.service.TomYzTableService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.youlai.boot.system.model.form.TomTableForm;
import com.youlai.boot.system.model.query.TomTableQuery;
import com.youlai.boot.system.model.vo.TomTableVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 汤姆代取前端控制层
 *
 * @author youlaitech
 * @since 2025-09-16 22:36
 */
@Tag(name = "汤姆代取接口")
@RestController
@RequestMapping("/api/v1/tomTables")
@RequiredArgsConstructor
public class TomTableController {

    private final TomTableService tomTableService;

    private final TomYzTableService tomYzTableService;

    @Operation(summary = "汤姆代取分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('system:tomTable:query')")
    public PageResult<TomTableVO> getTomTablePage(TomTableQuery queryParams) {
        IPage<TomTableVO> result = tomTableService.getTomTablePage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增汤姆代取")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('system:tomTable:add')")
    public Result<Void> saveTomTable(@RequestBody @Valid TomTableForm formData) {
        boolean result = tomTableService.saveTomTable(formData);
        return Result.judge(result);
    }

    @Operation(summary = "获取汤姆代取表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('system:tomTable:edit')")
    public Result<TomTableForm> getTomTableForm(
            @Parameter(description = "汤姆代取ID") @PathVariable Long id
    ) {
        TomTableForm formData = tomTableService.getTomTableFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改汤姆代取")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('system:tomTable:edit')")
    public Result<Void> updateTomTable(
            @Parameter(description = "汤姆代取ID") @PathVariable Long id,
            @RequestBody @Validated TomTableForm formData
    ) {
        boolean result = tomTableService.updateTomTable(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除汤姆代取")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('system:tomTable:delete')")
    public Result<Void> deleteTomTables(
            @Parameter(description = "汤姆代取ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = tomTableService.deleteTomTables(ids);
        return Result.judge(result);
    }

    @Operation(summary = "导出汇总表")
    @GetMapping("/exportHz")
    @PreAuthorize("@ss.hasPerm('system:tomTable:hz-download')")
    public void exportHz(TomTableQuery queryParams, HttpServletResponse response) throws IOException {
        if (Objects.isNull(queryParams.getZdId())) {
            throw new BusinessException("请选择驿站名称!");
        }
        TomYzTable tomYzTable = tomYzTableService.getById(queryParams.getZdId());
        List<TomTableVO> list = tomTableService.exportHzList(queryParams);

        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/exportHz.xlsx");
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "_" + tomYzTable.getName() + "汇总表.xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(list);
    }

    @Operation(summary = "导出地址表")
    @GetMapping("/exportDz")
    @PreAuthorize("@ss.hasPerm('system:tomTable:dz-download')")
    public void exportDz(TomTableQuery queryParams, HttpServletResponse response) throws IOException {
        if (Objects.isNull(queryParams.getZdId())) {
            throw new BusinessException("请选择驿站名称!");
        }
        TomYzTable tomYzTable = tomYzTableService.getById(queryParams.getZdId());
        List<TomTableVO> list = tomTableService.exportDzList(queryParams);

        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/exportDz.xlsx");
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "_" + tomYzTable.getName() + "地址表.xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(list);
    }
}
